import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:x3_base_core/base_theme/base_body_theme.dart';

class BaseTextArea extends StatefulWidget {
  /// 提示信息文本
  final String hintText;

  /// 值
  final String value;

  /// 是否只读
  final bool readOnly;

  /// 是否计算字数
  final bool isCount;

  /// 最大字数
  final int maxLength;

  /// 是否有边框
  final bool isBorder;

  /// 是否默认获取焦点
  final bool autoFocus;

  /// 点击完成按钮的点击事件
  final void Function(String value) onEditingComplete;

  final void Function(String value) onChanged;

  /// 把该输入框的焦点暴露出去
  final void Function(FocusNode focusNode) emitFocusNode;

  final TextInputType keyboardType;

  final int maxLines;

  const BaseTextArea({
    Key key,
    this.hintText = '请输入...',
    this.autoFocus = false,
    this.readOnly = false,
    this.isBorder = false,
    this.isCount = true,
    this.maxLength = 128,
    this.onEditingComplete,
    this.onChanged,
    this.emitFocusNode,
    this.value,
    this.keyboardType = TextInputType.multiline,
    this.maxLines = 4,
  })  : assert(maxLines > 1),
        super(key: key);
  @override
  _BaseTextAreaState createState() => _BaseTextAreaState();
}

class _BaseTextAreaState extends State<BaseTextArea> {
  FocusNode _focusNode = FocusNode();

  TextEditingController _textEditingController;

  String _textFieldValue;

  @override
  void initState() {
    _textEditingController = new TextEditingController(text: widget.value);

    /// 固定写法 监听焦点事件
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (widget.emitFocusNode != null) {
        widget.emitFocusNode(this._focusNode);
      }
    });
    this._textFieldValue = widget.value ?? '';
    super.initState();
  }

  @override
  void didUpdateWidget(covariant BaseTextArea oldWidget) {
    if (widget.value != oldWidget.value) {
      _textEditingController.text = widget.value;
    }
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    return Theme(
      data: ThemeData(highlightColor: Colors.transparent, splashColor: Colors.transparent),
      child: Container(
        padding: widget.readOnly == true ? EdgeInsets.symmetric(vertical: 8) : EdgeInsets.zero,
        child: TextFormField(
          autofocus: widget.autoFocus,
          controller: _textEditingController,
          keyboardType: widget.keyboardType,
          style: widget.readOnly == true ? Theme.of(context).textTheme.bodyText2.copyWith(color: BaseBodyTheme.subTextColor) : Theme.of(context).textTheme.bodyText2,
          maxLines: widget.maxLines,
          maxLength: widget.maxLength,
          maxLengthEnforcement: MaxLengthEnforcement.enforced,
          //maxLengthEnforced: true,
          inputFormatters: <TextInputFormatter>[
            TextInputFormatter.withFunction(
              (_, TextEditingValue newValue) {
                return newValue.copyWith(
                  composing: !newValue.composing.isCollapsed && widget.maxLength > newValue.composing.start ? TextRange(start: newValue.composing.start, end: math.min(newValue.composing.end, widget.maxLength)) : TextRange.empty,
                );
              },
            ),
          ],
          enabled: true,
          readOnly: widget.readOnly,
          decoration: InputDecoration(
            enabledBorder: widget.isBorder == false ? InputBorder.none : _inputBorder(color: BaseBodyTheme.greyBackgroundColor),
            focusedBorder: widget.isBorder == false ? InputBorder.none : _inputBorder(), // input 边框
            counterText: widget.isCount == true ? '${_textEditingController.text.length}/${widget.maxLength}' : '', //位于右下方显示的文本，常用于显示输入的字符数量
            counterStyle: Theme.of(context).textTheme.subtitle2.copyWith(fontSize: 11),
            hintText: widget.hintText, // 文本提示
            hintStyle: Theme.of(context).inputDecorationTheme.hintStyle,
            contentPadding: widget.isBorder == true ? EdgeInsets.all(6) : EdgeInsets.symmetric(vertical: 6),
            fillColor: Colors.transparent,
            filled: false,
            //位于输入框尾部的控件，同样的不能和suffixText同时使用
            suffixIconConstraints: BoxConstraints(maxWidth: 20),
            isDense: false, // 紧凑型
          ),
          onChanged: (value) {
            setState(() {
              _textFieldValue = value;
            });
            if (widget.onChanged != null) widget.onChanged(value);
          },
          onEditingComplete: _onEditingComplete,
        ),
      ),
    );
  }

  OutlineInputBorder _inputBorder({Color color}) {
    BorderRadius _circular = BorderRadius.circular(3);
    double _borderWidth = 1;
    return OutlineInputBorder(borderRadius: _circular, borderSide: BorderSide(width: _borderWidth, color: color ?? BaseBodyTheme.subTextColor));
  }

  /// 点击键盘右下角按钮的事件
  void _onEditingComplete() {
    if (widget.onEditingComplete != null) {
      widget.onEditingComplete(_textEditingController.text);
    }
  }

  @override
  void dispose() {
    _textEditingController.dispose();
    _focusNode.dispose();
    super.dispose();
  }
}
